package com.woniuxy.opencv.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.opencv.mapper.ParkingOrderMapper;
import com.woniuxy.opencv.pojo.ParkingOrder;
import com.woniuxy.opencv.pojo.ParkingRecord;
import com.woniuxy.opencv.service.ParkingOrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

@Slf4j
@Service
public class ParkingOrderServiceImpl extends ServiceImpl<ParkingOrderMapper, ParkingOrder> 
    implements ParkingOrderService {

    @Override
    @Transactional
    public ParkingOrder createOrder(ParkingRecord record, double fee) {
        log.info("开始创建停车订单 - 车牌号: {}, 订单号: {}, 费用: {}", 
            record.getPlateNumber(), record.getOrderId(), fee);
            
        ParkingOrder order = new ParkingOrder();
        order.setId(record.getOrderId());  // 使用ParkingRecord中的orderId
        order.setLicencePlate(record.getPlateNumber());
        order.setFee(fee);
        order.setDoPay(0); // 0: 未支付
        order.setCreateTime(new Date());
        
        // 保存订单
        save(order);
        log.info("停车订单创建成功 - 订单号: {}", order.getId());
        
        return order;
    }

    @Override
    public ParkingOrder getById(Long orderId) {
        ParkingOrder order = baseMapper.selectById(orderId);
        if (order != null) {
            log.info("查询到订单信息 - 订单号: {}, 车牌号: {}, 费用: {}, 支付状态: {}", 
                order.getId(), order.getLicencePlate(), order.getFee(), order.getDoPay());
        } else {
            log.warn("未查询到订单信息 - 订单号: {}", orderId);
        }
        return order;
    }

    @Override
    @Transactional
    public boolean updateOrderStatus(String orderId, Integer status) {
        Long orderIdLong;
        try {
            orderIdLong = Long.parseLong(orderId);
        } catch (NumberFormatException e) {
            log.error("订单号格式错误: {}", orderId);
            return false;
        }
        ParkingOrder order = getById(orderIdLong);
        if (order == null) {
            log.error("订单不存在 - 订单号: {}", orderId);
            return false;
        }
        // 更新状态
        order.setDoPay(status);
        if (status == 1) { // 已支付
            order.setPayTime(new Date());
        }
        // 保存更新
        boolean result = updateById(order);
        return result;
    }
}




